package com.winxuan.channel.support.interceptor.security;

import java.util.Collection;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

@Component("myAccessDecisionManager")
public class MyAccessDecisionManager implements AccessDecisionManager{
	private Logger log = LoggerFactory.getLogger(Thread.class);
	@Override
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes) throws AccessDeniedException,
			InsufficientAuthenticationException {
		if(configAttributes == null ){
			return;
		}
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();
		while(iterator.hasNext()){
			ConfigAttribute attribute = iterator.next();
			String needRole = ((SecurityConfig)attribute).getAttribute();
			for(GrantedAuthority grantedAuthority : authentication.getAuthorities()){
				if(needRole.equals(grantedAuthority.getAuthority())){
					return;
				}
			}
		}
		log.warn("Permissions Denied! 没有权限!");
		throw new AccessDeniedException("Permissions Denied! 没有权限!");
	}

	@Override
	public boolean supports(ConfigAttribute arg0) {
		return true;
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

}
